// server/controllers/directoryController.js
const fs = require('fs')
const path = require('path')
const allowedFolders = [
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven',
  'eight',
  'ten',
  'twelve',
  'sixteen',
  'twentyfour'
]

const BASE_DIR = path.join(__dirname, '../data')

// 获取目录树
exports.getTree = (req, res) => {
  const generateTree = (dirPath) => {
    const items = fs.readdirSync(dirPath)
    return items
      .map((item) => {
        const fullPath = path.join(dirPath, item)
        const isDirectory = fs.statSync(fullPath).isDirectory()

        if (isDirectory && allowedFolders.includes(item)) {
          return {
            id: fullPath,
            label: item,
            type: 'folder',
            children: generateTree(fullPath)
          }
        } else if (item.endsWith('.json')) {
          return {
            id: fullPath,
            label: item,
            type: 'file',
            folder: path.basename(dirPath)
          }
        }
      })
      .filter(Boolean)
  }

  try {
    const treeData = generateTree(BASE_DIR)
    res.json({ success: true, data: treeData })
  } catch (error) {
    res.status(500).json({ success: false, message: '生成目录树失败' })
  }
}

// 获取目录下的 JSON 文件数据
exports.getDirectory = (req, res) => {
  const { folder } = req.params

  if (!allowedFolders.includes(folder)) {
    return res.status(404).json({ success: false, message: '目录不存在' })
  }

  const folderPath = path.join(BASE_DIR, folder)

  if (!fs.existsSync(folderPath)) {
    return res.status(404).json({ success: false, message: '目录不存在' })
  }

  try {
    const files = fs.readdirSync(folderPath).filter((file) => file.endsWith('.json'))
    const data = files.map((file) => {
      const filePath = path.join(folderPath, file)
      const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
      return { fileName: file, content }
    })
    res.json({ success: true, data })
  } catch (error) {
    res.status(500).json({ success: false, message: '读取目录内容失败' })
  }
}

// 删除目录
exports.deleteDirectory = (req, res) => {
  const { folder } = req.params
  const folderPath = path.join(BASE_DIR, folder)

  if (!fs.existsSync(folderPath)) {
    return res.status(404).json({ success: false, message: '目录不存在' })
  }

  try {
    fs.rmSync(folderPath, { recursive: true, force: true })
    res.json({ success: true, message: `目录 ${folder} 已成功删除` })
  } catch (error) {
    res.status(500).json({ success: false, message: '删除目录失败' })
  }
}
